package com.dd.keel.core.common.utils;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Date util
 * @author Kevin.XU
 *
 */
public class DateUtil {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
	
	final static public int SECOND = Calendar.SECOND;
	final static public int MINUTE = Calendar.MINUTE;
	final static public int HOUR   = Calendar.HOUR_OF_DAY;
	final static public int DAY    = Calendar.DAY_OF_MONTH;
	final static public int MONTH  = Calendar.MONTH;
	final static public int YEAR   = Calendar.YEAR;
	
	final static public int MILLI_MICRO_SECONDS_PER_SECOND = 1000 * 1000; /*每秒含的微秒数*/
	final static public int MILLI_SECONDS_PER_SECOND       = 1000;        /*每秒含的毫秒数*/
	
	public static long randomTime() {
		return (long)(Math.random()*1000);
	}
	
	public static long randomTime(int seconds) {
		return (long)(Math.random()*seconds*1000);
	}
	
	public static Date revertFromSeconds(String seconds_str) throws Exception
	{
		long seconds = Long.parseLong(seconds_str);
		return new Date(seconds * 1000);
	}
	
	public static String convertToSeconds(Date date)
	{
		if(date!=null)
		{
			long mili_seconds = date.getTime();
			return mili_seconds/1000 + "";
		}
		else
		{
			return "";
		}
	}
	
	/**
	 * 把日期字符串转换为另一种格式
	 * @param oldFormat
	 * @param newForamt
	 * @param dateString
	 * @return
	 */
	public static String transformDateFormat(String oldFormat,String newForamt,String dateString) throws Exception 
	{
		Date date = getDatetime(dateString,oldFormat);
		return getDatetimeText(date,newForamt);
	}
	
	public static String getNow(String format)
	{
		if(format==null || format.equals(""))
		{
			format = "yyyyMMddHHmmss";
		}
		String temp = null;
		try{
			java.util.Date now = new java.util.Date();
			java.text.SimpleDateFormat dateformat= new java.text.SimpleDateFormat(format);
			temp = dateformat.format(now);
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		return temp;
	}
	
	public static boolean exceedDistance(Date firstDate,Date secondDate,long limitMiliSeconds)
	{
		long distance = firstDate.getTime() - secondDate.getTime();
		if(distance>limitMiliSeconds)
		{
			return true;
		}
		return false;
	}
	
	public static Date getDatetime(String source,String format) throws Exception 
	{
		java.text.SimpleDateFormat dateformat= new java.text.SimpleDateFormat(format);
		return dateformat.parse(source);
	}
	
	public static Date getDatetime(SimpleDateFormat dateformat,String source) throws Exception 
	{
		return dateformat.parse(source);
	}
	
	public static String getDatetimeText(Date source,String format)
	{
		String datetime = null;
		try{
			java.text.SimpleDateFormat dateformat= new java.text.SimpleDateFormat(format);
			datetime = dateformat.format(source);
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		return datetime;
	}
	
	public static Date addTime(Date source,int time_type,int amount)
	{
		if(source==null)
		{
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(source);
		cal.add(time_type, amount);
		return cal.getTime();
	}
	
	/**
	 * interval time expression is like '+30*60' , or '-1000'
	 * @param source
	 * @param intervalTimeExp
	 * @return
	 */
	public static Date addTime(Date source,String intervalTimeExp) 
	{
		if(source==null) return null;
		if(intervalTimeExp==null) return source;
		intervalTimeExp = intervalTimeExp.trim();
		int flag = 1;
		if(intervalTimeExp.charAt(0)=='-')
		{
			flag = -1;
			intervalTimeExp = intervalTimeExp.substring(1);
		}else if(intervalTimeExp.charAt(0)=='+'){
			intervalTimeExp = intervalTimeExp.substring(1);
		}
		int amount = 1;
		String[] numberArray = intervalTimeExp.split("\\*");
		try{
			for(int i=0; i<numberArray.length; ++i)
			{
				amount *= Integer.parseInt(numberArray[i]);
			}
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(source);
		cal.add(SECOND, amount*flag);
		return cal.getTime();
	}	
	
	public static long getCommandDatetime()
	{
		String datetime_str = DateUtil.getNow("MMddHHmmss");
		//System.out.println(datetime_str);
		return Long.parseLong(datetime_str);
	}
	
	public static long getCommandDatetime(long time)
	{
		String datetime_str = DateUtil.getDatetimeText(new Date(time), "MMddHHmmss");
		return Long.parseLong(datetime_str);
	}
	
	public static long getCommandDatetime(Date source)
	{
		long temp = 0;
		String datetime_str = DateUtil.getDatetimeText(source, "MMddHHmmss");
		//System.out.println(datetime_str);
		return Long.parseLong(datetime_str);
	}
	
	public static long getCommandDatetime(String mmddhhmmss)
	{
		mmddhhmmss = mmddhhmmss.trim();
		/*while(mmddhhmmss.startsWith("0"))
		{
			mmddhhmmss = mmddhhmmss.substring(1);
		}*/
		return Long.parseLong(mmddhhmmss);
	}
	public static Date stringToDate(String strValue) {
		if (strValue==null) {
			return null;
		}
		SimpleDateFormat clsFormat = null;
		if (strValue.length() > 19)
			strValue = strValue.substring(0, 19);
		if (strValue.length() == 19)
			clsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		else if (strValue.length() == 10)
			clsFormat = new SimpleDateFormat("yyyy-MM-dd");
		else if (strValue.length() == 14)
			clsFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		else if (strValue.length() == 8)
			clsFormat = new SimpleDateFormat("yyyyMMdd");

		ParsePosition pos = new ParsePosition(0);
		return clsFormat.parse(strValue, pos);
	}
	
	public static String dateToString(Date dteValue, String strFormat) {
		SimpleDateFormat clsFormat = new SimpleDateFormat(strFormat);
		return clsFormat.format(dteValue);
	}
	
	public static Date getYesterday() {
		Date d = new Date();
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - 1);
		return now.getTime();
	}
    /**
     * before today
     * @param day
     * @return
     */
	public static Date getDateBefore(int day) {
		Date d = new Date();
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();
	}
	
	public static Date getDateBefore(Date d,int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();
	}

	public static Date getDateAfter(int day) {
		Date d = new Date();
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
		return now.getTime();
	}
	
	public static Date getDateAfter(Date d, int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
		return now.getTime();
	}
	
	public static Date getDateAfterMonth(Date d, int month) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.MONTH, now.get(Calendar.MONTH) + month);
		return now.getTime();
	}
}
